#include "pcinfo.h"

#include <QProcess>
#include <QtEndian>

#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <string>
#include <fstream>

#ifdef __linux
#include <unistd.h>
#endif

PcInfo::PcInfo() {}

static bool get_cpu_id_by_asm(std::string & cpu_id)
{
    return(true);
}

static void parse_cpu_id(const char * file_name, const char * match_words, std::string & cpu_id)
{
    cpu_id.c_str();

    std::ifstream ifs(file_name, std::ios::binary);
    if (!ifs.is_open())
    {
        return;
    }

    char line[4096] = { 0 };
    while (!ifs.eof())
    {
        ifs.getline(line, sizeof(line));
        if (!ifs.good())
        {
            break;
        }

        const char * cpu = strstr(line, match_words);
        if (NULL == cpu)
        {
            continue;
        }
        cpu += strlen(match_words);

        while ('\0' != cpu[0])
        {
            if (' ' != cpu[0])
            {
                cpu_id.push_back(cpu[0]);
            }
            ++cpu;
        }

        if (!cpu_id.empty())
        {
            break;
        }
    }

    ifs.close();
}

static bool get_cpu_id_by_system(std::string & cpu_id)
{
    cpu_id.c_str();

    const char * dmidecode_result = ".dmidecode_result.txt";
    char command[512] = { 0 };
    snprintf(command, sizeof(command), "dmidecode -t 4 | grep ID > %s", dmidecode_result);

    if (0 == system(command))
    {
        parse_cpu_id(dmidecode_result, "ID:", cpu_id);
    }

    remove(dmidecode_result);

    return(!cpu_id.empty());
}

static bool get_cpu_id(std::string & cpu_id)
{
    int ret;
    if (get_cpu_id_by_asm(cpu_id))
    {
        return(true);
    }
    // ret = getuid();
    if (0 == ret)
    {
        if (get_cpu_id_by_system(cpu_id))
        {
            return(true);
        }
    }
    return(false);
}


QString PcInfo::GetCpuId()
{
    std::string cpu_id;
    get_cpu_id(cpu_id);
    return QString(cpu_id.c_str());
}

QString PcInfo::GetHardDiskId()
{
    QString queryDiskCmd = "wmic diskdrive get SerialNumber";
    QProcess process;
    process.start(queryDiskCmd);
    process.waitForStarted();
    process.waitForFinished();
    QString str = process.readAllStandardOutput();
    return str;
}
